<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

         <el-form-item label="岗位名称" prop="postName">
            <el-input style="width:200px" v-model="queryParams.postName" placeholder="请输入岗位名称" clearable
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="岗位状态" clearable>
               <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:post:add']">新增</el-button>
         </el-col>

         <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
         </el-col>

         <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
               v-hasPermi="['system:post:remove']">删除</el-button>
         </el-col>

         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table fit border v-loading="loading" :data="postList" @selection-change="handleSelectionChange" max-height="600">
         <el-table-column type="selection" width="50" align="center" />
         <el-table-column label="岗位标识" align="center" prop="postCode" width="150" />
         <el-table-column label="岗位名称" align="center" prop="postName" width="150" />
         <el-table-column label="所属部门" align="center" prop="deptName"></el-table-column>
         <el-table-column label="显示顺序" align="center" prop="postSort" width="150" />
         <el-table-column label="状态" align="center" prop="status" width="150">
            <template #default="scope">
               <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
            </template>
         </el-table-column>
         <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
            <template #default="scope">
               <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:post:edit']">修改</el-button>
               <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:post:remove']">删除</el-button>
            </template>
         </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
         @pagination="getList" />

      <!-- 新增或修改岗位对话框 -->
      <el-dialog :title="title" v-model="open" width="800px" append-to-body>
         <el-form ref="postRef" :model="form" :rules="rules" label-width="100px">

            <el-row>
               <el-col :span="24">
                  <el-form-item label="所属部门" prop="deptId">
                     <el-tree-select v-model="form.deptId" value-key="id" :data="options"
                        :props="{ value: 'id', label: 'label', children: 'children' }" :render-after-expand="false"
                        @change="selectDept"></el-tree-select>
                  </el-form-item>
               </el-col>
            </el-row>

            <el-row :gutter="30">

               <el-col :span="12">
                  <el-form-item label="岗位标识" prop="postCode">
                     <template #label>
                        <span>
                           <el-tooltip content="只支持小写字母,数字,下划线组合" placement="bottom">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           岗位标识
                        </span>
                     </template>
                     <el-input v-model="form.postCode" placeholder="请输入编码名称" />
                  </el-form-item>
               </el-col>

               <el-col :span="12">
                  <el-form-item label="岗位名称" prop="postName">
                     <el-input v-model="form.postName" placeholder="请输入岗位名称" />
                  </el-form-item>
               </el-col>

            </el-row>

            <el-row :gutter="30">

               <el-col :span="12">
                  <el-form-item label="显示顺序" prop="postSort">
                     <el-input-number v-model="form.postSort" controls-position="right" :min="0" />
                  </el-form-item>
               </el-col>

               <el-col :span="12">
                  <el-form-item label="岗位状态" prop="status">
                     <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
                        }}</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
            </el-row>

            <!-- 角色 -->
            <el-form-item label="岗位角色" prop="roleIdList">
               <el-select v-model="form.roleIdList" @change="selectPostRole" multiple style="width: 100%;">
                  <el-option v-for="item in postRoleArray" :key="item.roleId" :label="item.roleName"
                     :value="item.roleId"></el-option>
               </el-select>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
               <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
         </el-form>

         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFormDebounceHandler">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Post">
import { listPost, addPost, delPost, getPost, updatePost, getDepartment } from "@/api/system/post";
import { deptTreeSelect } from "@/api/system/user"
import { listRole } from "@/api/system/role"
import { getUser } from "@/api/system/user"
import { getCurrentInstance } from "vue";

console.log(getCurrentInstance(), "<<<=== getCurrentInstance");

const { proxy } = getCurrentInstance();//proxy相当于是当前组件的实例对象，而且里面的数据是响应式的
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
import { debounce } from "@/utils/debounce.js";

const options = ref([])
const postRoleArray = ref([])//角色数组
// const roleIdList=ref([])//选中岗位
// const deptId=ref("22")//选中部门
const postList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);//多选数组
const single = ref(true);//针对多选的修改按钮
const multiple = ref(true);//针对多选的删除按钮
const total = ref(0);
const title = ref("");

const data = reactive({
   form: {},
   queryParams: {
      pageNum: 1,
      pageSize: 10,
      postName: undefined,
      status: undefined
   },
   rules: {
      postName: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }],
      postSort: [{ required: true, message: "岗位顺序不能为空", trigger: "blur" }],
      deptId: [{
         required: true,
         message: "部门不能为空",
         trigger: "blur"
      }],
      postCode: [{
         required: true,
         validator: validatePostSign,
         trigger: "blur"
      }],
      roleIdList: [{
         required: true,
         message: "岗位角色不能为空",
         trigger: "blur"
      }]
   }
});

const { queryParams, form, rules } = toRefs(data);

/**岗位标识输入校验方法 */
function validatePostSign(rule, value, callback) {
   // 只支持小写字母,数字,下划线的组合
   const pattern = /^[a-z0-9_]+$/
   // console.log(rule,"<<<=== rule");
   // console.log(value,"<<<=== value");
   // console.log(callback,"<<<=== callback");

   if (!value) {
      callback(new Error("岗位标识不能为空"))
   } else {
      if (!pattern.test(value)) {
         callback(new Error("只支持小写字母,数字,下划线的组合"))
      } else {
         callback()

      }

   }

}

/**拿到角色列表数据 */
function getListRole() {
   listRole().then((res) => {
      console.log(res, "res <<<=== 拿到角色列表数据");
      postRoleArray.value = res.rows
   }).catch((error) => {
      console.log(error, "<<<=== 角色列表-error");
   })

}

/**拿到全部的部门下拉树形结构 */
function getDeptTreeSelect() {
   deptTreeSelect().then((res) => {
      console.log(res, "res <<<=== 拿到全部的部门下拉树形结构");
      options.value = res.data
   })
}

/**所属部门-下拉选中事件 */
function selectDept(val) {
   console.log(val, "<<<=== 部门选中");
}


/**岗位角色-下拉选中事件 */
function selectPostRole(val) {
   console.log(val, "<<<=== 岗位角色下拉选中");
}



/** 查询岗位列表 */
function getList() {
   loading.value = true;
   listPost(queryParams.value).then(res => {
      console.log(res, "<<<=== res 岗位列表数据");
      postList.value = res.rows;
      total.value = res.total;
      loading.value = false;
   });
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
/** 表单重置 */
function reset() {

   form.value = {
      roleIdList: [],//岗位下拉选中
      deptId: undefined,//部门下拉选中
      postId: undefined,//岗位唯一标识
      postName: undefined,
      postSort: 0,
      status: "0",
      remark: undefined
   };
   proxy.resetForm("postRef");
}
/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageNum = 1;
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
}


/** 多选框选中数据 */
function handleSelectionChange(selection) {
   console.log(selection, "<<<=== selection数组");
   ids.value = selection.map(item => item.postId);
   console.log(ids, "<<<=== 过滤后的ids postId多选数组");
   single.value = selection.length != 1;
   multiple.value = !selection.length;
}


/** 新增按钮操作 */
function handleAdd() {
   reset();
   open.value = true;
   title.value = "新增岗位";
}


/** 修改按钮操作 */
function handleUpdate(row) {
   console.log(row, "<<<===row 修改 表格当前行的数据");
   reset();
   const postId = row.postId || ids.value;
   console.log(postId, "<<<=== postId 修改");
   // getPost()是回显
   getPost(postId).then(res => {
      console.log(res, "<<<=== res 回显");
      form.value = res.data;
      open.value = true;
      title.value = "修改岗位";
   });
}


/** 提交按钮 */
const submitFormDebounceHandler = debounce(submitForm, 500);
function submitForm() {
   console.log(proxy, "<<<=== proxy-当前组件实例对象-还是响应式的");
   console.log(proxy.$refs.postRef, "<<<=== proxy.$refs.postRef");
   proxy.$refs.postRef.validate((valid) => {
      console.log(valid, "<<<=== valid");
      if (valid) {

         // 新增岗位的时候不传postId，因为新增成功完后端才生成postId,修改的时候要传postId,通过postId来判断当前是新增操作还是修改操作
         if (form.value.postId != undefined) {
            // 修改操作
            updatePost(form.value).then((res) => {
               console.log(res, "<<<=== res 修改拿到的值");
               proxy.$modal.msgSuccess("修改成功")
               open.value = false//关闭弹框
               getList()//重新请求列表数据
            }).catch((error) => {
               console.log(error, "<<<=== 修改请求报错");
            })
         } else {
            // 新增操作
            addPost(form.value).then((res) => {
               console.log(res, "<<<===新增-res");
               proxy.$modal.msgSuccess("新增成功")
               open.value = false
               getList()
            })
         }
      }
   })

}



/** 删除按钮操作 */
function handleDelete(row) {
   console.log(row, "<<<=== 删除拿到当前行row");
   const postIds = row.postId || ids.value;//可以是单个的字符串，也可以是一个数组
   console.log(postIds, "<<<=== postIds");
   proxy.$modal.confirm('是否确认删除岗位数据？').then(function () {
      return delPost(postIds);
   }).then((res) => {
      console.log(res, "<<<=== res 删除");
      getList();//重新请求数据
      proxy.$modal.msgSuccess("删除成功");
   }).catch((error) => {
      console.log(error, "<<<=== error 删除请求");
   });
}


getList();
getDeptTreeSelect()
getListRole()
</script>

<style scoped lang="scss">
.el-select {
   width: 100%;
}
</style>
